package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.IdsHandler;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;

/**
 * @author DL5O
 * @version 1.0
 */
@RestController
@Slf4j
@RequestMapping("/dish")
public class DishController {
    @Autowired
    private DishService dishService;

  /*  @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private CategoryService categoryService;*/

    @Autowired
    private RedisTemplate redisTemplate;

    @CacheEvict(value = "dishCache", allEntries = true)
    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto) {
//      log.info(dishDto.toString());
        dishService.saveWithFlavor(dishDto);

        //优化：把redis中的缓存清除，save方法会新增菜品信息，一旦新增，
        //就需要从数据库中重新查询数据，如果不移除redis中的数据，那么下次读取到的数据是未增加前的数据
        //String key = "dish_" + dishDto.getCategoryId()+"_" + dishDto.getStatus();
        //redisTemplate.delete(key);
        /*Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);*/
        return R.success("新增菜品成功");
    }

    /**
     * 分页查询
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/page")
    @Cacheable(value = "dishCache",
            key = "'dishPage_'+ #page + '_' + #pageSize + '_' + #name",
            unless = "#result.getCode() == 0")
    public R<Page<DishDto>> getPage(Integer page, Integer pageSize, @RequestParam(defaultValue = "") String name) {
        //1.构造分页构造器对象
        Page<DishDto> dishDtoPage = dishService.getPage(page, pageSize, name);
        return dishDtoPage != null ? R.success(dishDtoPage) : R.error("未知错误");
    }

    /**
     * 在编辑时进行菜品信息的回显
     *
     * @param id 菜品id
     * @return
     */
    @Cacheable(value = "dishCache",
            key = "'dish_'+ #id",
            unless = "#result.getCode() == 0")
    @GetMapping("/{id}")
    public R<DishDto> getDishDtoById(@PathVariable Long id) {
        DishDto dishDto = dishService.getDishDtoById(id);
        return dishDto != null ? R.success(dishDto) : R.error("未知错误");
    }

    /**
     * 编辑菜单信息
     *
     * @param dishDto
     * @return
     */
    @CacheEvict(value = "dishCache", allEntries = true)
    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto) {
        dishService.updateWithFlavor(dishDto);
        //移除redis中的 key 为 dish_菜品id_状态 的缓存数据

        //精确清理
        /*String key = "dish_" + dishDto.getCategoryId()+"_" + dishDto.getStatus();
        redisTemplate.delete(key);*/

        //清除以dish开头的所有缓存
        /*Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);*/
        return R.success("修改成功");
    }

    /**
     * 单条/多条 起售或停售
     * @param status
     * @param ids
     * @return
     */
    @CacheEvict(value = "dishCache", allEntries = true)
    @PostMapping("/status/{status}")
    public R<String> updateStatus(@PathVariable Integer status, String ids) {
        List<Long> list = IdsHandler.handleIds(ids);
        dishService.updateStatus(status, list);
        /*//清除redis中的缓存
        Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);*/
        return R.success("成功");
    }

    /**
     * 删除一条/多条
     *
     * @param ids
     * @return
     */
    @CacheEvict(value = "dishCache", allEntries = true)
    @DeleteMapping
    public R<String> deleteByIds(@RequestParam List<Long> ids) {
        dishService.removeWithFlavor(ids);
        //清理缓存
        /*Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);*/
        return R.success("删除成功");
    }

    /**
     * 根据菜品分类 查询对应的菜品，并展示到添加菜品窗口中
     *
     * @param dish
     * @return
     */
    @GetMapping("/list")
    @Cacheable(value = "dishCache",
            key = "#dish.categoryId +'_' + #dish.status",
            unless = "#result.getCode() == 0")
    @Transactional
    public R<List<DishDto>> getList(Dish dish) {
        List<DishDto> listDtoList = null;
        /*String key = "dish_" + dish.getCategoryId() + "_" + dish.getStatus();//dish_1397844263642378242_1
        log.info("dishKey={}",key);//拼接key*/

        //优化：先从redis中获取数据
        //listDtoList =(List<DishDto>) redisTemplate.opsForValue().get(key);

        //如果存在，则直接返回，无需查询数据库
        if (listDtoList != null) {
            return R.success(listDtoList);
        }

        //如果不存在，需要查询数据库，将查询到的菜品数据缓存到redis
        listDtoList = dishService.getList(dish);
        //redisTemplate.opsForValue().set(key,listDtoList);
        return listDtoList != null ? R.success(listDtoList) : R.error("查询错误");
    }

}
